package cn.demarcia.coco.uihelper;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.demarcia.coco.AppConfig;


/**
 * 图片处理工具类
 */
public class ImageUtils {
    /**
     * 请求相册
     */
    public static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 9162;
    /**
     * 请求相机
     */
    public static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
    /**
     * 请求裁剪
     */
    public static final int REQUEST_CODE_GETIMAGE_BYCROP = 6709;

    public static void saveBitmap(String filePath, Bitmap bitmap, int quality) throws IOException {
        if (bitmap != null) {
            FileOutputStream fos = new FileOutputStream(filePath);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
            byte[] bytes = stream.toByteArray();
            fos.write(bytes);
            fos.close();
        }
    }


    //保存ImageView中的图片

    public static Boolean saveBitmap(String filePath, int quality, ImageView imageView) {
        Boolean isSaved = false;
        Drawable drawable = imageView.getDrawable();
        if (drawable == null) {
            return false;
        }

        FileOutputStream outputStream = null;
        File file = new File(filePath);
        if (file.isDirectory()) {        //如果是目录，不允许保存
            return false;
        }

        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            outputStream = new FileOutputStream(file);
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            //bitmap.recycle();  不需要回收bitMap http://www.oschina.net/question/565065_67273
            isSaved = true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        //通知图库更刷新数据
        try {
            MediaStore.Images.Media.insertImage(imageView.getContext().getContentResolver(), file.getAbsolutePath(), filePath, null);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return isSaved;
    }


    //保存View中的图片
    public static Boolean saveBitmap(View view, int quality, String filePath) {

        Boolean isSuccess = false;

        //创建对应大小的bitmap
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        //存储
        FileOutputStream outputStream = null;
        File file = new File(filePath);
        if (file.isDirectory()) {
            return false;//如果是目录，则不允许保存
        }

        try {
            outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            isSuccess = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //bitmap.recycle();不需要回收bitMap http://www.oschina.net/question/565065_67273
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return isSuccess;
    }

    /**/
    public static Bitmap loadImgThumbnail(String path, int cropX, int cropY) {
        Bitmap bitmap = getBitmapByPath(path);
        return zoomBitmap(bitmap, cropX, cropY);
    }

    /*放大缩小图片*/
    private static Bitmap zoomBitmap(Bitmap bitmap, int cropX, int cropY) {
        Bitmap newBitmap = null;
        if (bitmap != null) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            Matrix matrix = new Matrix();
            float scaleHeight = ((float) cropY / height);
            float scaleWidth = ((float) cropX / width);
            matrix.postScale(scaleWidth, scaleHeight);
            newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        }
        return newBitmap;
    }

    public static Bitmap getBitmapByPath(String path) {
        return getBitmapByPath(path, null);
    }

    private static Bitmap getBitmapByPath(String path, BitmapFactory.Options options) {
        FileInputStream fis;
        Bitmap bitmap = null;
        try {
            File file = new File(path);
            fis = new FileInputStream(file);
            bitmap = BitmapFactory.decodeStream(fis, null, options);

        } catch (FileNotFoundException | OutOfMemoryError e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static String checkImageUrl(String imgUrl) {
        if (imgUrl.startsWith("http://")) {
            return imgUrl;
        } else {
            return AppConfig.SERVER_IMAGE + imgUrl;
        }
    }

    public static String checkLocalImageUrl(String imgUrl) {
        if (imgUrl.startsWith("http://")) {
            return imgUrl;
        } else {
            return "file://" + imgUrl;
        }
    }
}
